package com.youngball.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

import java.net.InetSocketAddress;

/**
 * Created by liaopingzhu on 2016/12/15.
 */
public class LightServer {

    public void start(int port) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workerGroup);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new ChannelInitializerImpl());
            b.option(ChannelOption.SO_BACKLOG, 128);
            b.childOption(ChannelOption.SO_KEEPALIVE, true);
            //绑定端口,同步等待成功
            ChannelFuture f = b.bind(new InetSocketAddress(port)).sync();
            System.out.println("========服务端5555启动=========");
            //使得我们的channel的register变成同步不可中断的
            f.channel().closeFuture().syncUninterruptibly();
            //等待服务器监听端口关闭
            f.channel().closeFuture().sync();
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
           new LightServer().start(5555);
    }

    final class ChannelInitializerImpl extends ChannelInitializer<SocketChannel>{

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            //支持java客户端发送命令的handle
            ch.pipeline().addLast(new ProtobufDecoder(CommandEntity.HardWare.LightRequest.getDefaultInstance()));
            ch.pipeline().addLast(new ProtobufEncoder());
            ch.pipeline().addLast(new LightServerInitHandler());
        }
    }
}
